package com.rfid.rfidbluetooth;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.rfid.base.base.BaseListActivity;
import com.rfid.base.base.BasePresenter;
import com.rfid.base.util.BaseUtil;
import com.rfid.base.util.LogUtils;
import com.rfid.rfidbluetooth.manager.BleClientManager;
import com.rfid.rfidbluetooth.manager.BleServerManager;
import com.rfid.rfidbluetooth.manager.BluetoothMAdapter;
import com.rfid.rfidbluetooth.manager.BluetoothManager;
import com.rfid.rfidbluetooth.manager.ToServerManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends BaseListActivity<BluetoothMAdapter, BluetoothDevice, BasePresenter> implements BluetoothManager.BluetoothListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("蓝牙列表");
//        LogUtils.init(this,"/sdcard/rfid");
        BluetoothManager.INSTANCE.setListener(this);
        BluetoothManager.INSTANCE.registerBluetooth(this);
        BleClientManager.INSTANCE.setListener(this);
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
//        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            System.out.println("reqqqq");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_SCAN,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.BLUETOOTH_CONNECT}, 100);
        } else {
            System.out.println("scan");
//            BluetoothManager.INSTANCE.startScan();
            BleClientManager.INSTANCE.startScanBle();
        }

        EventBus.getDefault().register(this);

        new Thread(new Runnable() {
            @Override
            public void run() {
                ToServerManager.INSTANCE.init();
            }
        }).start();
    }



    @Override
    public void onMsg(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this,"获取权限失败",Toast.LENGTH_SHORT).show();
        } else {
            BluetoothManager.INSTANCE.startScan();
        }
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected BluetoothMAdapter getAdapter() {
        return new BluetoothMAdapter(mData);
    }

    @Override
    protected int getRecyclerViewId() {
        return R.id.recyclerView;
    }

    @Override
    public void onDeviceFound(BluetoothDevice device) {
//        System.out.println("onDeviceFound");
        if (!mData.contains(device)) {
            if (!TextUtils.isEmpty(device.getName())) {
//                mData.add(0,device);
                mData.add(device);
                mAdapter.notifyDataSetChanged();
            } else {
//                mData.add(device);
            }

        }
    }

    boolean connect;
    @Override
    public void onClick(BluetoothDevice device) {
        try {
            BleClientManager.INSTANCE.stopScan();
            System.out.println("onClick " + device);
//            if (connect) {
//
//                BleClientManager.INSTANCE.sendHello();
//                return;
//            }
            BleClientManager.INSTANCE.connectBle(this,device);
            connect = true;
            onShowLoading("正在连接");
//            if (true){
//                return;
//            }
//            onShowLoading("正在连接：" + device.getName());
//            new AsyncTask<Void, Void, Boolean>() {
//                @Override
//                protected Boolean doInBackground(Void... voids) {
//                    try {
//                        BluetoothManager.INSTANCE.connect(device.getAddress());
//                        return true;
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(MainActivity.this,e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                    }
//                    return false;
//                }
//
//                @Override
//                protected void onPostExecute(Boolean aBoolean) {
//                    if (aBoolean) {
//                        Toast.makeText(MainActivity.this,"连接成功",Toast.LENGTH_SHORT).show();
//                        BaseUtil.startActivity(MainActivity.this,RfidListActvitiy.class,null);
//                    }
//                    onHideLoading();
//                }
//            }.execute();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this,e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDiscoveryFinished() {
    }

    @Override
    public void onConnect(boolean connect) {
        onHideLoading();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,connect?"连接成功":"连接断开",Toast.LENGTH_SHORT).show();
                if (connect) {
                    BaseUtil.startActivity(MainActivity.this,RfidListActvitiy.class,null);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.setting) {
            BaseUtil.startActivity(this,SettingActivity.class,null);
        }
        return super.onOptionsItemSelected(item);
    }

    public void button(View view) {
//        BluetoothManager.INSTANCE.startScan();
//        BluetoothManager.INSTANCE.actAsServer();
        BleServerManager.INSTANCE.startServer(this);
        Toast.makeText(MainActivity.this,"启动服务",Toast.LENGTH_SHORT).show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTipMsg(String msg) {
        System.out.println(msg);
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("onDestroy");
        EventBus.getDefault().unregister(this);
        BleClientManager.INSTANCE.closeBle();
    }
}